from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
import re

from .models import Users

def get_user_by_account(account):
    """依据手机号或用户名查询用户"""
    try:
        if re.match(r'^1[3-9]\d{9}$',account):
            user = Users.objects.get(mobile=account)
        else:
            user = Users.objects.get(username=account)
    except Users.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义后端认证"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写此方法"""
        user = get_user_by_account(username)

        if user and user.check_password(password):
            return user


def generate_verify_email_url(user):
        """利用itsdangerous对数据加密，对当前传入的user生成激活邮箱url"""
        serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
        data = {"user_id":user.id, "email":user.email}   # 加密的数据包装成字典
        data_sign = serializer.dumps(data).decode()    #  该数据为bytes
        # settings.EMAIL_VERIFY_URL   dev配置中设置
        verify_url = settings.EMAIL_VERIFY_URL + "?token=" + data_sign  # 路由拼接
        return verify_url


def check_token_to_user(token):
    """解密，传入token返回user"""
    serializer = Serializer(settings.SECRET_KEY,3600)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else: # 获取数据
        user_id = data.get("user_id")
        email = data.get("email")
        try:  # 将获取的数据与数据库数据比对
            user = Users.objects.get(id=user_id,email=email) # get 为找到抛出异常
        except Users.DoesNotExist:
            return None
        else:  # 找到返回user对象
            return user



